import { Battle, BattleUser } from '@/types/battle'
import { battleUserStore } from '../store/battle'
import { battleskillStore } from '@/store/skill'
import { Skill } from '@/types/skill'
import { PaginatedData, PaginationResponse } from '@/types'
import { ROUTE_APP } from '@/lib/consts'

//query%7B%22desc%22:[%22updated_at%22],%22page%22:1%7D
export async function battleRecord(query: {
  desc?: string[]
  page?: number
  size?: number
}): Promise<PaginatedData<Battle>> {
  try {
    const defaultParams = {
      desc: ['updated_at'],
      page: 1,
      size: 10,
      ...query
    }
    const paramsStr = JSON.stringify(defaultParams)
    const response = await fetch(`${ROUTE_APP}/battle?query=${paramsStr}`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json'
      }
    })
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    const data: PaginationResponse<Battle> = await response.json()
    return data.data
  } catch (error) {
    console.error('Error fetching battle items:', error)
    throw error
  }
}

// save battle record  {data: {name: string, path: string}}
export async function battleSave({
  data
}: {
  data: { id?: number; title: string; path: string; status?: number }
}) {
  const { id, title, path, status = 1 } = data
  try {
    const method = id && id > 0 ? 'PUT' : 'POST'
    const uri =
      id && id > 0 ? `${ROUTE_APP}/battle/${id}` : `${ROUTE_APP}/battle`
    const response = await fetch(uri, {
      method: method,
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ id, title, path, status })
    })

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    const responseData = await response.json()
    return responseData
  } catch (error) {
    console.error('Error saving battle record:', error)
  }
}

//  get all battle_user
export async function battleUser() {
  try {
    const users = battleUserStore.getState().storeUsers
    if (users.length > 500) {
      return users
    }
    // size= 2000
    const paramsStr = JSON.stringify({ size: 2000 })
    const response = await fetch(
      '/rpi/g/moji-user/battle_user?query=' + paramsStr,
      {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json'
        }
      }
    )
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    const data = await response.json()
    data.data.items.forEach((item: BattleUser) => {
      battleUserStore.getState().addUser(item)
    })
    return data
  } catch (error) {
    console.error('Error fetching battle user:', error)
  }
}

// battle user save
export async function battleUserSave({
  data
}: {
  data: { name: string; status?: number; role?: number }
}) {
  const { name, status = 1, role = 0 } = data
  try {
    const response = await fetch('/rpi/battle_user', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ name, status, role })
    })

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    const responseData = await response.json()
    return responseData
  } catch (error) {
    console.error('Error saving battle user:', error)
  }
}

// battle user save
export async function battleUserUpdate({
  data
}: {
  data: { id: number; name: string; role?: number; status?: number }
}) {
  const { id, name, role, status = 1 } = data
  try {
    ///rpi/battle_user/
    const response = await fetch(`/rpi/battle_user/${id}`, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ id, name, status, role })
    })

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    const responseData = await response.json()
    return responseData
  } catch (error) {
    console.error('Error saving battle user:', error)
  }
}

// battle_skill
export async function battleSkill() {
  const skills = battleskillStore.getState().storeSkills
  if (skills.length > 50) {
    return skills
  }
  try {
    const paramsStr = JSON.stringify({ size: 200 })
    const response = await fetch('/rpi/battle_skill?query=' + paramsStr, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json'
      }
    })
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    const data = await response.json()
    data.data.items.forEach((item: Skill) => {
      battleskillStore.getState().addSkill(item)
    })
    return data
  } catch (error) {
    console.error('Error fetching battle skill:', error)
  }
}

// battle-detail
export async function battleDetail(id: string) {
  try {
    const response = await fetch(`/rpi/battle_detail/${id}`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json'
      }
    })
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    const data = await response.json()
    return data
  } catch (error) {
    console.error('Error fetching battle detail:', error)
  }
}

// battle-detail save
export async function battleDetailSave({
  data
}: {
  data: { id: number; content: string; status?: number }
}) {
  const { id, content, status = 1 } = data
  try {
    // url: /rpi/battle_detail/{id}
    const response = await fetch(`/rpi/battle_detail/${id}`, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ id, content, status })
    })

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    const responseData = await response.json()
    return responseData
  } catch (error) {
    console.error('Error saving battle detail:', error)
  }
}
